// frontend/src/admin/CheckinDetails.js

import React, { useState, useEffect, useCallback } from 'react';
import { Card, Descriptions, Button, Modal, Form, Select, InputNumber, message, Table, Popconfirm, Tag } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { adminAPI } from '../services/api';
import moment from 'moment';

const { Option } = Select;

const CheckinDetails = () => {
    const { id } = useParams(); // 获取入住单号 (checkin_id) 从 URL
    const navigate = useNavigate(); // 用于退房后导航
    const [checkin, setCheckin] = useState(null);
    const [consumptions, setConsumptions] = useState([]);
    const [menuItems, setMenuItems] = useState([]); // 所有可供选择的商品
    const [loading, setLoading] = useState(false);
    const [isAddConsumptionModalVisible, setIsAddConsumptionModalVisible] = useState(false);
    const [consumptionForm] = Form.useForm();

    // New states for custom checkout confirmation modal
    const [isCheckoutConfirmModalVisible, setIsCheckoutConfirmModalVisible] = useState(false);


    const fetchCheckinDetails = useCallback(async () => {
        try {
            const { data } = await adminAPI.getCheckinById(id);
            setCheckin(data);
        } catch (error) {
            console.error('获取入住详情失败:', error);
            message.error('获取入住详情失败: ' + (error.response?.data?.message || error.message));
        }
    }, [id]);

    const fetchConsumptions = useCallback(async () => {
        try {
            const { data } = await adminAPI.getConsumptionsByCheckin(id);
            setConsumptions(data);
        } catch (error) {
            console.error('获取消费记录失败:', error);
            message.error('获取消费记录失败: ' + (error.response?.data?.message || error.message));
        }
    }, [id]);

    const fetchMenuItems = useCallback(async () => {
        try {
            const { data } = await adminAPI.getAllMenuItems();
            setMenuItems(data);
        } catch (error) {
            console.error('获取商品列表失败:', error);
            message.error('获取商品列表失败: ' + (error.response?.data?.message || error.message));
        }
    }, []);

    const fetchData = useCallback(async () => {
        setLoading(true);
        try {
            await Promise.all([
                fetchCheckinDetails(),
                fetchConsumptions(),
                fetchMenuItems()
            ]);
        } catch (error) {
            // 错误已经由各个 fetch 函数处理
        } finally {
            setLoading(false);
        }
    }, [fetchCheckinDetails, fetchConsumptions, fetchMenuItems]);

    useEffect(() => {
        fetchData();
    }, [fetchData]);

    const handleAddConsumption = () => {
        consumptionForm.resetFields();
        setIsAddConsumptionModalVisible(true);
    };

    const onAddConsumptionFinish = async (values) => {
        setLoading(true);
        try {
            const selectedItem = menuItems.find(item => item.item_id === values.item_id);
            if (!selectedItem) {
                message.error('选择的商品不存在。');
                setLoading(false);
                return;
            }

            const consumptionData = {
                checkin_id: id,
                item_id: values.item_id,
                quantity: values.quantity,
            };
            await adminAPI.addConsumption(consumptionData);
            message.success('消费记录添加成功');
            setIsAddConsumptionModalVisible(false);
            consumptionForm.resetFields();
            fetchData(); // 重新获取所有数据，包括消费列表和总金额
        } catch (error) {
            console.error('添加消费记录失败:', error);
            message.error(error.response?.data?.message || '添加消费记录失败');
        } finally {
            setLoading(false);
        }
    };

    const handleDeleteConsumption = async (consumptionId) => {
        setLoading(true);
        try {
            await adminAPI.deleteConsumption(consumptionId);
            message.success('消费记录删除成功');
            fetchData(); // 刷新数据
        } catch (error) {
            console.error('删除消费记录失败:', error);
            message.error(error.response?.data?.message || '删除消费记录失败');
        } finally {
            setLoading(false);
        }
    };

    // Function to show the custom checkout confirmation modal
    const showCheckoutConfirmModal = () => {
        if (checkin.status === '已退房') {
            message.warn('该入住记录已退房，无需重复操作。');
            console.log(`[Frontend Debug CD] Checkin already checked out: ${checkin.checkin_id}`);
            return;
        }
        console.log(`[Frontend Debug CD] Checkout button clicked for checkinId: ${checkin.checkin_id}`);
        setIsCheckoutConfirmModalVisible(true);
    };

    // Function to handle confirmation from the custom modal
    const handleConfirmCheckout = async () => {
        console.log(`[Frontend Debug CD] Custom Modal confirmed for checkinId: ${checkin.checkin_id}`);
        setLoading(true);
        try {
            const checkoutTime = moment().format('YYYY-MM-DD HH:mm:ss');
            console.log(`[Frontend Debug CD] Preparing to send checkout request for checkinId: ${checkin.checkin_id} with checkoutTime: ${checkoutTime}`);
            await adminAPI.checkoutGuest(checkin.checkin_id, { check_out_time: checkoutTime });
            message.success('退房成功');
            console.log(`[Frontend Debug CD] Checkout request succeeded for checkin_id: ${checkin.checkin_id}`);
            setIsCheckoutConfirmModalVisible(false); // Close the modal
            navigate('/admin/checkins'); // 退房成功后导航回入住管理列表
        } catch (error) {
            console.error(`[Frontend Debug CD] Error during checkout for checkinId: ${checkin.checkin_id}:`, error);
            message.error(error.response?.data?.message || '退房失败');
        } finally {
            setLoading(false);
            console.log(`[Frontend Debug CD] Checkout attempt finished for checkinId: ${checkin.checkin_id}`);
        }
    };

    // Function to cancel from the custom modal
    const handleCancelCheckoutConfirmModal = () => {
        console.log(`[Frontend Debug CD] Custom Modal cancelled for checkinId: ${checkin.checkin_id}`);
        setIsCheckoutConfirmModalVisible(false);
    };


    const consumptionColumns = [
        { title: '商品名称', dataIndex: 'item_name', key: 'item_name' },
        { title: '数量', dataIndex: 'quantity', key: 'quantity' },
        { title: '单价 (¥)', dataIndex: 'unit_price', key: 'unit_price', render: price => `¥${parseFloat(price || 0).toFixed(2)}` },
        { title: '总金额 (¥)', dataIndex: 'amount', key: 'amount', render: amount => `¥${parseFloat(amount).toFixed(2)}` },
        { title: '消费时间', dataIndex: 'consume_time', key: 'consume_time', render: text => moment(text).format('YYYY-MM-DD HH:mm:ss') },
        {
            title: '操作',
            key: 'actions',
            render: (_, record) => (
                checkin && checkin.status === '入住中' && (
                    <Popconfirm
                        title="确定删除此消费记录吗？"
                        onConfirm={() => handleDeleteConsumption(record.consumption_id)}
                        okText="是"
                        cancelText="否"
                    >
                        <Button icon={<DeleteOutlined />} danger size="small" />
                    </Popconfirm>
                )
            ),
        },
    ];

    if (loading && !checkin) {
        return <div style={{ textAlign: 'center', padding: '50px' }}>加载中...</div>;
    }

    if (!checkin) {
        return <div style={{ textAlign: 'center', padding: '50px', color: '#888' }}>未找到入住详情。</div>;
    }

    return (
        <div style={{ padding: '20px' }}>
            <Button onClick={() => navigate('/admin/checkins')} style={{ marginBottom: 16 }}>
                返回入住管理
            </Button>
            <h1>入住详情 - {checkin.room_number} ({checkin.guest_name})</h1>

            <Card
                title="入住信息"
                variant="bordered" /* Removed inline comment */
                style={{ marginBottom: 20 }}
                extra={
                    checkin.status === '入住中' && (
                        <Button type="primary" onClick={showCheckoutConfirmModal} loading={loading}>
                            办理退房
                        </Button>
                    )
                }
            >
                <Descriptions variant="bordered" column={{ xs: 1, sm: 2, md: 3 }} size="small">
                    <Descriptions.Item label="入住单号">{checkin.checkin_id}</Descriptions.Item>
                    <Descriptions.Item label="房间号">{checkin.room_number}</Descriptions.Item>
                    <Descriptions.Item label="房间类型">{checkin.room_type}</Descriptions.Item>
                    <Descriptions.Item label="客户姓名">{checkin.guest_name}</Descriptions.Item>
                    <Descriptions.Item label="身份证号">{checkin.id_card}</Descriptions.Item>
                    <Descriptions.Item label="联系电话">{checkin.phone || '未登记'}</Descriptions.Item>
                    <Descriptions.Item label="入住时间">{moment(checkin.checkin_date).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
                    <Descriptions.Item label="预离时间">{checkin.expected_checkout_time ? moment(checkin.expected_checkout_time).format('YYYY-MM-DD HH:mm:ss') : 'N/A'}</Descriptions.Item>
                    <Descriptions.Item label="实际离店时间">
                        {checkin.checkout_date ? moment(checkin.checkout_date).format('YYYY-MM-DD HH:mm:ss') : '未退房'}
                    </Descriptions.Item>
                    <Descriptions.Item label="当前总金额">{`¥${parseFloat(checkin.total_amount || 0).toFixed(2)}`}</Descriptions.Item>
                    <Descriptions.Item label="状态">
                        <Tag color={checkin.status === '入住中' ? 'blue' : 'green'}>{checkin.status}</Tag>
                    </Descriptions.Item>
                </Descriptions>
            </Card>

            <Card
                title="消费记录"
                variant="bordered" /* Removed inline comment */
                extra={
                    checkin.status === '入住中' && (
                        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddConsumption}>
                            添加消费
                        </Button>
                    )
                }
                loading={loading}
            >
                <Table
                    columns={consumptionColumns}
                    dataSource={consumptions}
                    rowKey="consumption_id"
                    pagination={false}
                    locale={{ emptyText: '暂无消费记录' }}
                />
            </Card>

            {/* 添加消费记录的Modal */}
            <Modal
                title="添加消费记录"
                open={isAddConsumptionModalVisible}
                onCancel={() => {
                    setIsAddConsumptionModalVisible(false);
                    consumptionForm.resetFields();
                }}
                footer={null}
                destroyOnHidden={true} /* Removed inline comment */
            >
                <Form
                    form={consumptionForm}
                    layout="vertical"
                    onFinish={onAddConsumptionFinish}
                >
                    <Form.Item
                        name="item_id"
                        label="选择商品"
                        rules={[{ required: true, message: '请选择商品' }]}
                    >
                        <Select placeholder="请选择商品" showSearch optionFilterProp="children" loading={loading}>
                            {menuItems.map(item => (
                                <Option key={item.item_id} value={item.item_id}>
                                    {item.item_name} (¥{parseFloat(item.price).toFixed(2)})
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="quantity"
                        label="数量"
                        rules={[{ required: true, message: '请输入数量' }, { type: 'number', min: 1, message: '数量必须大于0' }]}
                    >
                        <InputNumber min={1} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            添加
                        </Button>
                        <Button
                            onClick={() => {
                                setIsAddConsumptionModalVisible(false);
                                consumptionForm.resetFields();
                            }}
                            style={{ marginLeft: 8 }}
                        >
                            取消
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

            {/* Custom Checkout Confirmation Modal */}
            <Modal
                title="确认退房"
                open={isCheckoutConfirmModalVisible}
                onOk={handleConfirmCheckout}
                onCancel={handleCancelCheckoutConfirmModal}
                okText="确定"
                cancelText="取消"
                confirmLoading={loading}
                destroyOnHidden={true}
            >
                <p>您确定要为该入住记录办理退房吗？退房后将无法再添加消费。</p>
            </Modal>
        </div>
    );
};

export default CheckinDetails;
